<template>
  <div>
    <div class="h-100 page-box flex-column">
      <div class="btns-line">
        <el-button type="primary" icon="el-icon-plus" @click="showAddDataSource"
          >新增数据源</el-button
        >
      </div>
      <div class="flex-1 flow-y-auto">
        <data-table
          ref="table"
          :pageObj="params"
          @modifyItem="modifyItem"
          @deleteItem="deleteItem"
          element-loading-text="加载中..."
          height="580"
          v-bind="tableOptions"
          v-loading="tableLoading"
          :updateCallback="getDataSourceList"
        ></data-table>
      </div>
    </div>
    <el-dialog
      :visible.sync="createDataSourceVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      @close="dialogClose"
      custom-class="selfDialog"
      width="500px"
      v-loading="dialogLoading"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item
          prop="dataSourceName"
          label="名称"
          :rules="rules.dataSourceName"
        >
          <el-input
            v-model="form.dataSourceName"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="connectionType"
          label="连接类型"
          :rules="rules.connectionType"
        >
          <el-select v-model="form.connectionType" placeholder="请选择连接类型" style="width: 100%;">
            <el-option label="RestFul类型" :value="1"></el-option>
            <el-option label="Mysql类型" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="protocol"
          label="协议"
          :rules="rules.protocol"
          v-if="form.connectionType === 1"
        >
          <el-select v-model="form.protocol" placeholder="请选择协议" style="width: 100%;">
            <el-option label="http协议" :value="1"></el-option>
            <el-option label="https协议" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="ip"
          label="IP"
          :rules="rules.ip"
        >
          <el-input
            v-model="form.ip"
            placeholder="请输入IP"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="port"
          label="端口"
          :rules="rules.port"
        >
          <el-input
            v-model="form.port"
            placeholder="请输入端口"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="url"
          label="默认路径"
          :rules="rules.url"
          v-if="form.connectionType === 1"
        >
          <el-input
            v-model="form.url"
            placeholder="请输入默认路径"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="dbName"
          label="数据库名"
          :rules="rules.dbName"
          v-if="form.connectionType === 2"
        >
          <el-input
            v-model="form.dbName"
            placeholder="请输入数据库名"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="dbUserName"
          label="用户名"
          :rules="rules.dbUserName"
          v-if="form.connectionType === 2"
        >
          <el-input
            v-model="form.dbUserName"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="dbPassword"
          label="密码"
          :rules="rules.dbPassword"
          v-if="form.connectionType === 2"
        >
          <el-input
            v-model="form.dbPassword"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="charset"
          label="字符集编码"
          :rules="rules.charset"
          v-if="form.connectionType === 2"
        >
          <el-input
            v-model="form.charset"
            placeholder="请输入字符集编码"
          ></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDataSourceVisible = false" size="mini"
          >取消</el-button
        >
        <el-button @click="subForm" size="mini" type="primary">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDataSourceList, setDataSourceItem, delDataSourceItem  } from "@/api/formApi";
import { validateIllegality, validateIp, validatePort } from "@/utils/validate";
import { confirm } from "@/utils/tools";

export default {
  name: 'dataSourceManage',
  data() {
    const dbNameValidator = (rule, value, callback) => {
      let reg = /^(?!\d+$)[\da-zA-Z_]+/g
      if (reg.test(value)) {
        return callback()
      }else{
        return callback(new Error('数据库名称不合法'))
      }
    }
    return {
      params: {
        page: 1,
        size: 10,
        total: 0
      },
      searchData: {
        factoryId: window.localStorage.factoryId
      },
      tableLoading: false,
      tableOptions: {
        tableData: [],
        modifySettings: [
          {
            eventName: "modifyItem",
            name: "编辑",
            btnType: "",
            code: "mes-systemConfig-middleWare-btn_edit"
          },
          {
            eventName: "deleteItem",
            name: "删除",
            btnType: "danger",
            code: "mes-systemConfig-middleWare-btn_edit"
          }
        ],
        _columns: [
          {
            prop: "dataSourceName",
            label: "数据源名称"
          },
          {
            prop: "connectionTypeLabel",
            label: "连接类型"
          },
          {
            prop: "ip",
            label: "IP"
          },
          {
            prop: "port",
            label: "端口"
          }
        ]
      },
      rules: {
        dataSourceName: [
          {
            required: true,
            min: 1,
            max: 64,
            message: "请输入64个字符以内的名称",
            trigger: "blur"
          },
          { validator: validateIllegality, trigger: "blur" }
        ],
        connectionType: {required: true, trigger: 'blur', message: '请选择数据源类型'},
        protocol: {required: true, trigger: 'blur', message: '请选择协议'},
        ip: [
          {
            required: true,
            message: "请输入IP",
            trigger: "blur"
          },
          { validator: validateIp, trigger: "blur" }
        ],
        port: [
          {
            required: true,
            message: "请输入端口",
            trigger: "blur"
          },
          { validator: validatePort, trigger: "blur" }
        ],
        url: [
          {
            min: 0,
            max: 64,
            message: "路径不能超过64个字符",
            trigger: "blur"
          },
        ],
        dbName: [
          {
            required: true,
            min: 1,
            max: 64,
            message: "请输入64个字符以内的名称",
            trigger: "blur"
          },
          {
            validator: dbNameValidator,
            trigger: 'blur'
          }
        ],
        dbUserName: [
          {
            required: true,
            min: 1,
            max: 64,
            message: "请输入64个字符以内的用户名",
            trigger: "blur"
          },
        ],
        dbPassword: [
          {
            required: true,
            min: 1,
            max: 64,
            message: "请输入64个字符以内的密码",
            trigger: "blur"
          },
        ],
        charset: [
          {
            required: true,
            min: 1,
            max: 16,
            message: "请输入16个字符以内的字符集编码",
            trigger: "blur"
          }
        ]
      },
      form: {
        "charset": "utf8",
        "connectionType": 1,
        "dataSourceName": null,
        "dbName": null,
        "dbPassword": null,
        "dbUserName": null,
        "factoryId": window.localStorage.factoryId,
        "ip": null,
        "port": null,
        "protocol": 1,
        "url": null
      },
      createDataSourceVisible: false,
      isEdit: false,
      dialogTitle: "新建数据源",
      dialogLoading: false
    }
  },
  created() {
    this.getDataSourceList()
  },
  watch: {
    "form.connectionType"(val) {
      this.$refs.form && this.$refs.form.clearValidate();
    }
  },
  methods: {
    getDataSourceList() {
      this.tableLoading = true
      getDataSourceList(this.params, this.searchData).then(res => {
        this.tableLoading = false;
        this.tableOptions.tableData = res.data.rows;
        this.params.total = res.data.total;
        this.tableOptions.tableData.forEach(item => item.connectionTypeLabel = item.connectionType === 1 ? 'RestFul连接' : 'Mysql连接')
        if (this.params.page > 1 && res.data.rows.length === 0) {
          this.params.page--;
          this.getDataSourceList();
        }
      }).catch(err => {
        this.tableLoading = false
      })
    },
    modifyItem(item) {
      this.isEdit = true;
      this.dialogTitle = "编辑数据源";
      this.createDataSourceVisible = true;
      this.form = Object.assign({}, item);
    },
    deleteItem(item) {
      confirm("删除之后会影响相关接口且不可撤销，是否确定？").then(res => {
        delDataSourceItem({ dataSourceId: item.dataSourceId }).then(res => {
          this.$message({
            type: "success",
            message: "删除成功"
          });
          this.getDataSourceList();
        });
      });
    },
    showAddDataSource() {
      this.isEdit = false;
      this.createDataSourceVisible = true;
      this.dialogTitle = "新建数据源";
    },
    dialogClose() {
      this.form = {
        "charset": "utf8",
        "connectionType": 1,
        "dataSourceName": null,
        "dbName": null,
        "dbPassword": null,
        "dbUserName": null,
        "factoryId": window.localStorage.factoryId,
        "ip": null,
        "port": null,
        "protocol": 1,
        "url": null
      }
      this.dialogLoading = false
      this.$refs.form.resetFields()
    },
    subForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          this.form.factoryId = window.localStorage.factoryId
          setDataSourceItem(this.form).then(res => {
            this.createDataSourceVisible = false
            this.getDataSourceList()
          }).catch(err => {
            this.dialogLoading = false
          })
        }else{
          return false
        }
      })
    },

  }
}
</script>

<style lang='scss' scoped>
.page-box {
  padding: 10px;
}
</style>
